Ext.define('Seq.form.field.TreePicker', {
    extend: 'Ext.ux.TreePicker',
    xtype: 'xtreepicker',

    allowClear: true,
    store: Ext.create('Ext.data.TreeStore'), // 初值

    createPicker: function () {
        var me = this, picker = new Ext.tree.Panel(Ext.apply({
            baseCls: Ext.baseCSSPrefix + 'boundlist',
            shrinkWrapDock: 2,
            store: me.store,
            floating: true,
            displayField: me.displayField,
            columns: me.columns,
            minHeight: me.minPickerHeight,
            maxHeight: me.maxPickerHeight,
            manageHeight: false,
            shadow: false,
            listeners: {
                scope: me,
                itemclick: me.onItemClick,
                itemkeydown: me.onPickerKeyDown,
                selectionchange: me.onSelectionChange,
                // 增加选中前的判断
                beforeitemclick: me.onBeforeItemClick,
                beforeitemdbclick: me.onBeforeItemDbClick,
                beforeitemkeydown: me.onBeforePickerKeyDown,
                beforeselect: me.onBeforeSelect,
                load: me.onLoad,
                checkchange: me.onCheckchange
            }
        }, me.treecfg)), view = picker.getView();
        if (Ext.isIE9 && Ext.isStrict) {
            view.on({
                scope: me,
                highlightitem: me.repaintPickerView,
                unhighlightitem: me.repaintPickerView,
                afteritemexpand: me.repaintPickerView,
                afteritemcollapse: me.repaintPickerView
            });
        }
        return picker;
    },

    selectItem: function (record) {
        var me = this;

        if (me.checked) { // checked tree
            return;
        }

        me.record = record;
        me.setValue({
            id: record.data.id,
            name: record.data.text,
            clz: record.data.clz
        });
        me.setRawValue(record.data.text);
        me.fireEvent('select', me, record);
        me.collapse();
    },

    setValue: function (value) { // 默认value的输入格式都是{id:1, name:xxx}
        var me = this, record;
        if (me.checked) {
            me.setCheckedValue(value);
            return;
        }
        me.value = value;
        me.bind && me.bind.value.setValue(value); // 已知会导致二次触发setValue，但是因为value值相同，不会再次触发
        if (me.store.loading) {
            return me;
        }
        if (Ext.isEmpty(value)) {
            /*
             * record = me.store.getRoot(); me.value = { id : record.data.id, name : record.data.text };
             */
            me.value = null;
        } else {
            record = me.store.findNode('id', value.id);
        }

        me.setRawValue(record ? record.get(me.displayField) : (value ? value.name : ''));
        if (me.allowClear) {
            me.triggers.clear.setHidden(Ext.isEmpty(value));
        }
        return me;
    },

    removeValue: function (values, remove) {
        Ext.each(values, function (v) {
            if (v && (v.id == remove.id)) {
                Ext.Array.remove(values, v);
            }
        });
        return values;
    },

    setCheckedValue: function (value, checked) {
        var me = this;
        if (me.store.loading) {
            return me;
        }
        if (value == null || me.value == null) {
            me.value = [];
        } else {
            me.value = me.removeValue(me.value, value);
            if (checked) {
                me.value = Ext.Array.push(me.value, value);
            }
        }
        me.bind && me.bind.value.setValue(me.value);
        var rawStr = '';
        if (0 < me.value.length) {
            rawStr = me.value[0].name;
        }
        if (1 < me.value.length) {
            rawStr += Ext.util.Format.format('(+{0})', me.value.length);
        }
        me.setRawValue(rawStr);
        if (me.allowClear) {
            me.triggers.clear.setHidden(Ext.isEmpty(me.value));
        }
        return me;
    },

    onExpand: function () {
        var me = this, picker = me.picker, store = picker.store, value = me.value, node;

        if (value) {
            node = store.findNode('id', value.id);
        }

        if (!node) {
            node = store.getRoot();
        }

        if (!picker.rootVisible && 'root' == node.getId()) { // root visible false
            return;
        }
        node.parentNode.expand();
        picker.ensureVisible(node, {
            select: true,
            focus: true
        });
    },

    onSelectionChange: function (cmp, selected, opts) {
    },

    onBeforeItemClick: function (view, record, node, rowIndex, e) {
        return this.allowOfLevels(this.levels, record.data.clz);
    },

    onBeforeItemDbClick: function (view, record, node, rowIndex, e) {
        return this.allowOfLevels(this.levels, record.data.clz);
    },

    onBeforePickerKeyDown: function (view, record, item, index, e) {
        return this.allowOfLevels(this.levels, record.data.clz);
    },

    onBeforeSelect: function (view, record, index, eOpts) {
        return this.allowOfLevels(this.levels, record.data.clz);
    },

    onKeyup: function (view, e) {

    },

    allowOfLevels(levels, clz) {
        if (!Ext.isEmpty(levels)) {
            return Ext.Array.contains(levels, clz);
        }
        return true;
    },

    onCheckchange: function (node, checked, e, eOpts) {
        var me = this, levels = me.levels;
        if (!Ext.isEmpty(levels)) {
            if (!Ext.Array.contains(levels, node.data.clz)) {
                node.cascade(function (n) {
                    if (Ext.Array.contains(levels, n.data.clz)) {
                        me.setCheckedNode(n, checked);
                    }
                    n.set('checked', checked);
                });
                return;
            }
        }
        me.setCheckedNode(node, checked);
    },

    setCheckedNode: function (node, checked) {
        this.setCheckedValue({
            id: node.data.id,
            name: node.data.text
        }, checked);
    },

    // onLoad: function (view, records, successful, operation, node, eOpts) {
    //     var me = this;
    //     me.record && me.picker.getSelectionModel().select(me.record, false, true);
    // },

    updateStore: function (value) {
        var me = this;
        if (!Ext.isEmpty(value)) {
            me.store = value;
            me.mon(me.store, {
                scope: me,
                load: me.onLoad,
                update: me.onUpdate
            });
            if (me.getValue()) {
                me.setValue(me.getValue());
            }
        }
    },

    constructor: function (config) {
        var me = this;
        if (false != config.allowClear) {
            config.triggers = {
                clear: {
                    cls: 'x-form-clear-trigger',
                    width: '14px !important',
                    weight: -1,
                    hidden: true,
                    handler: function () {
                        var me = this;
                        if (me.picker) {
                            me.picker.getRootNode().cascade(function (node) {
                                if (node.data.checked) {
                                    node.set('checked', false);
                                }
                            });
                        }
                        me.setValue(null);
                    }
                }
            };
        }
        me.callParent(arguments);
    }

});
